package com.jt.tenant.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.jt.tenant.R;
import com.jt.tenant.app.JTApplication;
import com.jt.tenant.conn.GetLoginAdmin;
import com.jt.tenant.conn.GetVerificationCode;
import com.jt.tenant.widget.Tools;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.util.UtilToast;

import java.util.HashMap;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * Created by Administrator on 2016/3/1.
 */
public class LoginActivity extends JTActivity implements View.OnClickListener,PlatformActionListener {

    private EditText et_admin, et_pwd;

    private TextView go_login, go_register;//登录，注册

    private TextView login_account, login_phone, login_code, agreement;//账号密码登录，手机快捷登录，协议

    private ImageView iv_user;//账号图标

    private LinearLayout lin_agreement, lin_forget;//协议条，忘记密码条

    private String login_type;//登录方式

    private String openId = "";

    private GetLoginAdmin getLoginAdmin = new GetLoginAdmin(new AsyCallBack<GetLoginAdmin.Info>() {

        @Override
        public void onSuccess(String toast, int type, GetLoginAdmin.Info info) throws Exception {

            if (info.msg.equals("000")) {

                if(info.flag.equals("0")) {

                    if (!info.user_obdId.equals("") && !info.user_obdId.equals("null")) {

                        JPushInterface.setAliasAndTags(LoginActivity.this, info.user_phone, JTApplication.tag, new TagAliasCallback() {

                            @Override

                            public void gotResult(int i, String s, Set<String> set) {

                                Log.e("JPush开启", "Jpush status: " + i);//状态

                            }
                        });

                    }

                    //无论什么情况都保存账号
                    editor.putString("LoginUser", admin).commit();

                    if (login_flag == 0) {

                        editor.putString("LoginPwd", pwd).commit();

                    }

                    editor.putString("AutoLogin", "yes").commit();

                    //存储数据
                    JTApplication.jtPreferences.saveUserId(info.userId);

                    JTApplication.jtPreferences.saveHaveUid(true);

                    //saveObdId

                    JTApplication.jtPreferences.saveObdId(info.user_obdId);

                    if (!info.user_obdId.equals("") && !info.user_obdId.equals("null")) {

                        JTApplication.jtPreferences.saveHaveObdid(true);

                    } else {

                        JTApplication.jtPreferences.saveHaveObdid(false);

                    }
//                    //saveToken
                    JTApplication.jtPreferences.saveToken(info.session_token);

                    Log.e("TAG", "token=" + info.session_token + ",obdid=" + JTApplication.jtPreferences.readOdbID());
                    //savePhone
                    JTApplication.jtPreferences.savePhone(info.user_phone);
                    //nickname
                    JTApplication.jtPreferences.saveNickName(info.user_nickname);
                    //头像
                    JTApplication.jtPreferences.saveHeadPath(info.user_headpic);
                    //车牌号
                    JTApplication.jtPreferences.savePlateNum(info.car_plateNum);
                    //车架号
                    JTApplication.jtPreferences.saveVincode(info.car_vincode);
                    //车辆id
                    JTApplication.jtPreferences.saveCarId(info.car_id);

                    //城市编号
                    JTApplication.jtPreferences.saveCityCode(info.city_code);

                    //机动车号
                    JTApplication.jtPreferences.saveEngineCode(info.engine_code);

                    //性别
                    JTApplication.jtPreferences.saveSex(info.user_sex);

                    //车id
                    JTApplication.jtPreferences.saveCarId(info.carId);

                    //车的归属类型
                    JTApplication.jtPreferences.saveCarType(info.carType);

                    //车型id
                    JTApplication.jtPreferences.saveCategoryId(info.categoryId);

                    //城市
                    JTApplication.jtPreferences.saveCity(info.city);

                    //购买时间
                    JTApplication.jtPreferences.saveRemark(info.remark);

                    //账号状态
                    JTApplication.jtPreferences.saveAccountState(info.account_state);

                    JTApplication.jtPreferences.saveBSX(info.bsx);

                    JTApplication.jtPreferences.savePP(info.pp);

                    JTApplication.jtPreferences.savePL(info.pl);

                    JTApplication.jtPreferences.saveNK(info.nk);

                    JTApplication.jtPreferences.saveCX(info.cx);

                    //传送成功 存储图片路径
                    JTApplication.jtPreferences.saveHeadPath(info.user_headpic);

                    //存储 紧急账号(没用！！)
//                            JTApplication.jtPreferences.savePhone2(phone);
                    //存储 昵称
                    JTApplication.jtPreferences.saveNickName(info.user_nickname);

                    //存储 WIFI状态
                    JTApplication.jtPreferences.saveWIFI(info.wifi);

                    //存储 GPS隐私管理
                    if (info.gpsType.equals("0")) {

                        JTApplication.jtPreferences.savePrivacy(false);

                    } else {

                        JTApplication.jtPreferences.savePrivacy(true);

                    }


                    //存储 WIFI密码
                    JTApplication.jtPreferences.saveWIFIPWD(info.wifipwd);
                    //存储 积分
//                    JTApplication.jtPreferences.saveUserIntegral(info.user_integralCount,"1");

                    //存储保险状态
                    JTApplication.jtPreferences.saveInsFlag(info.baoxianFlag);

                    //存储驾驶证号
                    JTApplication.jtPreferences.saveDriverNum(info.driverNum);

                    //存储有效起始日期
                    JTApplication.jtPreferences.saveDriverEffectiveDate(info.driverEffectiveDate);
                    //存储有效期
                    JTApplication.jtPreferences.saveDriverEffectiveYear(info.driverEffectiveYear);
                    //性别
                    if (info.user_sex.equals("1")) {

                        JTApplication.jtPreferences.saveSex("男");

                    } else if (info.user_sex.equals("2")) {

                        JTApplication.jtPreferences.saveSex("女");

                    }

                    startActivity(new Intent(context, MainActivity.class));

                    JTApplication.jtPreferences.saveShockNum(Integer.parseInt(Tools.F_num(info.tCollisionRemindValue)));

                    JTApplication.jtPreferences.saveShockBool(Integer.parseInt(Tools.F_num(info.tCollisionRemindIsOpen)));

                    for (int i = 0; i < info.personSet.size(); i++) {

                        if (info.personSet.get(i).equals("0")) {

                            JTApplication.jtPreferences.saveMessage(true, String.valueOf(i + 1));

                        } else {

                            JTApplication.jtPreferences.saveMessage(false, String.valueOf(i + 1));

                        }


                    }


                    Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show();

                    finish();

                }else {

                    startActivity(new Intent(context,Register1Activity.class)

                            .putExtra("account",openId)

                            .putExtra("type",Integer.parseInt(login_type))

                    );

                }

            } else {

                Toast.makeText(context, info.msg, Toast.LENGTH_SHORT).show();

            }

        }

        @Override
        public void onFail(String toast, int type) throws Exception {

            UtilToast.show(context, "连接超时");

        }

    });

    private ImageView login_wechat, login_qq;

    private TextView title_name, register;

    private String admin, pwd;

    private TextView forget_pwd;

    private SharedPreferences.Editor editor;

    private SharedPreferences preferences;

    private int login_flag = 0;//登录方式 0：账号密码  1：手机号快捷登录

    private String identifying_code;//验证码

    private String account_flag;//账号状态,0:已激活，1：未激活

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);

        init_view();

    }

    private void init_view() {

        (title_name = (TextView) findViewById(R.id.tv_title_name)).setText("登录");

        (register = (TextView) findViewById(R.id.commit)).setText("注册");

        preferences = getSharedPreferences("tenant", MODE_PRIVATE);

        editor = preferences.edit();

        et_admin = (EditText) findViewById(R.id.et_admin);

        et_admin.clearFocus();

        et_pwd = (EditText) findViewById(R.id.et_pwd);

        et_admin.setText(preferences.getString("LoginUser", ""));

        et_pwd.setText(preferences.getString("LoginPwd", ""));

        (go_login = (TextView) findViewById(R.id.go_login)).setOnClickListener(this);

        (go_register = (TextView) findViewById(R.id.commit)).setOnClickListener(this);

        (forget_pwd = (TextView) findViewById(R.id.forget_pwd)).setOnClickListener(this);

        (login_account = (TextView) findViewById(R.id.tv_login_account)).setOnClickListener(this);

        (login_phone = (TextView) findViewById(R.id.tv_login_phone)).setOnClickListener(this);

        (login_code = (TextView) findViewById(R.id.tv_login_code)).setOnClickListener(this);

        (agreement = (TextView) findViewById(R.id.tv_login_agreement)).setOnClickListener(this);

        iv_user = (ImageView) findViewById(R.id.iv_login_user);

        lin_agreement = (LinearLayout) findViewById(R.id.lin_login_agreement);

        lin_forget = (LinearLayout) findViewById(R.id.lin_login_forget);

        (login_wechat = (ImageView) findViewById(R.id.iv_login_wechat)).setOnClickListener(this);

        (login_qq = (ImageView) findViewById(R.id.iv_login_qq)).setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            //忘记密码
            case R.id.forget_pwd:

                startActivity(new Intent(LoginActivity.this, Register1Activity.class)

                        .putExtra("type",3)

                        .putExtra("account","")

                );

                break;

            case R.id.go_login:

                admin = et_admin.getText().toString().trim();

                pwd = et_pwd.getText().toString().trim();

                if(login_flag == 0) {

                    if (admin.equals("")) {

                        Toast.makeText(this, "请输入账号", Toast.LENGTH_SHORT).show();

                    } else if (pwd.equals("")) {

                        Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();

                    } else if (pwd.length() < 6 || pwd.length() > 20) {

                        Toast.makeText(this, "密码为6-20位", Toast.LENGTH_SHORT).show();

                    } else if (!Tools.isMobile(admin)) {

                        Toast.makeText(this, "手机号格式错误", Toast.LENGTH_SHORT).show();

                    } else {

//                    startActivity(new Intent(this,MainActivity.class));

                        login_net(admin, pwd, "0");

                    }

                }else {

                    if(et_pwd.getText().toString().trim().equals(identifying_code)&&account_flag.equals("0")){

                        login_net(admin,"0","3");

                    }else if(et_pwd.getText().toString().trim().equals(identifying_code)&&account_flag.equals("1")){

                        startActivity(new Intent(LoginActivity.this, Register2Activity.class)

                                .putExtra("type",0)

                                .putExtra("account","0")

                                .putExtra("phone",admin)

                        );

                    }else {

                        UtilToast.show(context,"验证码错误");

                    }

                }

                break;

            case R.id.commit:

                startActivity(new Intent(context, Register1Activity.class)

                        .putExtra("type", 0)

                        .putExtra("account", "0")

                );

                break;

//            账号密码登录
            case R.id.tv_login_account:

                login_account.setBackgroundResource(R.drawable.bian_right_bottom_c4c4c4_ffffff);

                login_phone.setBackgroundResource(R.drawable.bian_bottom_c4c4c4_f5f5f5);

                iv_user.setImageResource(R.mipmap.icon_login_user);

                login_code.setVisibility(View.GONE);

                lin_agreement.setVisibility(View.GONE);

                lin_forget.setVisibility(View.VISIBLE);

                et_pwd.setText(preferences.getString("LoginPwd", ""));

                et_pwd.setHint("请输入密码");

                login_flag = 0;

                break;


//            手机号快捷登录
            case R.id.tv_login_phone:

                login_account.setBackgroundResource(R.drawable.bian_right_bottom_c4c4c4_f5f5f5);

                login_phone.setBackgroundResource(R.drawable.bian_bottom_c4c4c4_ffffff);

                iv_user.setImageResource(R.mipmap.icon_login_phone);

                login_code.setVisibility(View.VISIBLE);

                lin_agreement.setVisibility(View.VISIBLE);

                lin_forget.setVisibility(View.GONE);

                et_pwd.setText("");

                et_pwd.setHint("请输入验证码");

                login_flag = 1;

                break;


//            获取验证码
            case R.id.tv_login_code:

                if(Tools.isMobile(et_admin.getText().toString().trim())){

                    get_code_net();

                }else {

                    UtilToast.show(this,"请输入正确的手机号");

                }


                break;

//            点击协议
            case R.id.tv_login_agreement:


                break;

//            微信登录
            case R.id.iv_login_wechat:

                authorize(ShareSDK.getPlatform(Wechat.NAME),"1");

                break;

//            QQ登录
            case R.id.iv_login_qq:

                authorize(ShareSDK.getPlatform(QQ.NAME),"2");
                break;

        }

    }

    /***
     * 登陆接口
     */
    private void login_net(final String account, final String pwd, String type) {

        getLoginAdmin.phone = account;

        getLoginAdmin.password = pwd;

        getLoginAdmin.type = type;

//        getLoginAdmin.type = "3";

        getLoginAdmin.execute(context);

    }

    /***
     * 获取验证码
     */
    private void get_code_net() {

        new GetVerificationCode(et_admin.getText().toString().trim(), new AsyCallBack<GetVerificationCode.Info>() {

            @Override
            public void onSuccess(String toast, int type, GetVerificationCode.Info info) throws Exception {

                if (info.msg.equals("000")) {


                        UtilToast.show(context, "验证码已经发送到您的手机中");

                        identifying_code = info.authCode;

                        account_flag = info.flag;

                        first_get_code();


                } else {

                    UtilToast.show(context, info.msg);

                }
            }
        }).execute(this);

    }

    private void first_get_code() {

        new CountDownTimer(60000, 1000) {// 两个参数，前一个指倒计时的总时间，后一个指多长时间倒数一下。

            @Override
            public void onTick(long millisUntilFinished) {

                login_code.setText("重新获取(" + millisUntilFinished
                        / 1000 + ")");

                login_code.setEnabled(false);
            }

            @Override
            public void onFinish() {

                login_code.setText("重新获取验证码");

                login_code.setEnabled(true);

            }
        }.start();

    }

    private void authorize(Platform platform,String type){

        platform.removeAccount(true);

        platform.setPlatformActionListener(this);

        platform.showUser(null);

        this.login_type = type;

    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {

        Log.e("@@@@","onComplete");

        Log.e("@@@@",openId);

        openId = platform.getDb().getUserId();

        login_net(openId,"",login_type);

    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {

        Log.e("@@@@","onError");

        Log.e("@@@@",openId);

    }

    @Override
    public void onCancel(Platform platform, int i) {

        Log.e("@@@@","onCancel");

        Log.e("@@@@",openId);

    }
}
